package org.example.controller;

import jakarta.servlet.http.HttpServletResponse;
import org.example.service.InvestmentDataExcelService;
import org.example.service.InvestmentDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 投资数据控制器
 */
@RestController
@RequestMapping("/api/investment-data")
public class InvestmentDataController {


    @Autowired
    private InvestmentDataExcelService investmentDataExcelService;
    @Autowired
    private InvestmentDataService investmentDataService;

    /**
     * 导入Excel文件
     * @param file Excel文件
     * @return 导入结果
     */
    @PostMapping("/import")
    public ResponseEntity<Map<String, Object>> importData(@RequestParam("file") MultipartFile file) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 验证文件
            if (file.isEmpty()) {
                result.put("success", false);
                result.put("message", "文件不能为空");
                return ResponseEntity.badRequest().body(result);
            }

            // 验证文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null ||
                    (!originalFilename.endsWith(".xlsx") && !originalFilename.endsWith(".xls"))) {
                result.put("success", false);
                result.put("message", "文件格式不正确，请上传Excel文件(.xlsx或.xls)");
                return ResponseEntity.badRequest().body(result);
            }

            // 执行导入
            int count = investmentDataExcelService.importExcel(file);

            result.put("success", true);
            result.put("message", "导入成功");
            result.put("count", count);

            return ResponseEntity.ok(result);

        } catch (IOException e) {
            result.put("success", false);
            result.put("message", "文件读取失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 导出所有Excel文件
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("/export")
    public void exportData(HttpServletResponse response) throws IOException {
        investmentDataExcelService.exportExcel(response);
    }

    /**
     * 根据放款月范围导出Excel文件
     * @param startPeriod 开始放款月
     * @param endPeriod 结束放款月
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("/export/period-range")
    public void exportDataByPeriodRange(
            @RequestParam("startPeriod") String startPeriod,
            @RequestParam("endPeriod") String endPeriod,
            HttpServletResponse response) throws IOException {
        investmentDataExcelService.exportExcelByPeriodRange(startPeriod, endPeriod, response);
    }

    /**
     * 根据放款月导出Excel文件
     * @param periodDate 放款月
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @GetMapping("/export/period/{periodDate}")
    public void exportDataByPeriod(@PathVariable String periodDate, HttpServletResponse response) throws IOException {
        investmentDataExcelService.exportExcelByPeriod(periodDate, response);
    }

    /**
     * 清空指定放款月的数据
     * @param periodDate 放款月
     * @return 清空结果
     */
    @DeleteMapping("/clear/{periodDate}")
    public ResponseEntity<Map<String, Object>> clearData(@PathVariable String periodDate) {
        Map<String, Object> result = new HashMap<>();
        try {
            int deletedCount = investmentDataService.clearByPeriodDate(periodDate);
            result.put("success", true);
            result.put("message", "放款月 " + periodDate + " 数据已清空");
            result.put("deletedCount", deletedCount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "清空数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取指定放款月的数据
     * @param periodDate 放款月
     * @return 数据列表
     */
    @GetMapping("/data/period/{periodDate}")
    public ResponseEntity<Map<String, Object>> getDataByPeriod(@PathVariable String periodDate) {
        Map<String, Object> result = new HashMap<>();
        try {
            var dataList = investmentDataService.getByPeriodDate(periodDate);
            result.put("success", true);
            result.put("data", dataList);
            result.put("count", dataList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 根据放款月范围获取数据
     * @param startPeriod 开始放款月
     * @param endPeriod 结束放款月
     * @return 数据列表
     */
    @GetMapping("/data/period-range")
    public ResponseEntity<Map<String, Object>> getDataByPeriodRange(
            @RequestParam("startPeriod") String startPeriod,
            @RequestParam("endPeriod") String endPeriod) {
        Map<String, Object> result = new HashMap<>();
        try {
            var dataList = investmentDataService.getByPeriodRange(startPeriod, endPeriod);
            result.put("success", true);
            result.put("data", dataList);
            result.put("count", dataList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }

    /**
     * 获取所有数据
     * @return 数据列表
     */
    @GetMapping("/data/all")
    public ResponseEntity<Map<String, Object>> getAllData() {
        Map<String, Object> result = new HashMap<>();
        try {
            var dataList = investmentDataService.getAllData();
            result.put("success", true);
            result.put("data", dataList);
            result.put("count", dataList.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询数据失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(result);
        }
    }
}
